#include "Landscape8DirNode.h"
#include <cmath>

Landscape8DirNode::Landscape8DirNode() :_x(0), _y(0), _map(nullptr) 
{

}

float Landscape8DirNode::GoalDistanceEstimate( const Landscape8DirNode& goal ) const
{
	return abs(_x - goal._x) + abs(_y - goal._y);
}

bool Landscape8DirNode::IsGoal( const Landscape8DirNode& nodeGoal ) const
{
	return IsSameState( nodeGoal );
}

bool Landscape8DirNode::IsSameState( const Landscape8DirNode& other ) const
{
	return _x == other._x && _y == other._y;
}

float Landscape8DirNode::GetCost( const Landscape8DirNode& other ) const
{
	return _x == other._x || _y == other._y ? 1.0f : 1.41f;
}

bool Landscape8DirNode::GetSuccessors( ECS::AStarSearch<Landscape8DirNode>* search, const Landscape8DirNode* parentNode ) const
{
	static const int tile_offsets[9][2] = {{0,1}, {1, 1}, {1,0}, {1, -1}, {0,-1}, {-1, -1}, {-1,0}, {-1, 1}, {0,1}};

	for (unsigned int i = 0; i < 8; ++i)
	{
		int x = _x + tile_offsets[i][0];
		int y = _y + tile_offsets[i][1];

		if (_map->isValid(x, y) && 
			(i % 2 ? (	_map->isPassable(x, y) && 
						_map->isPassable(_x + tile_offsets[i - 1][0], _y + tile_offsets[i - 1][1]) && 
						_map->isPassable(_x + tile_offsets[i + 1][0], _y + tile_offsets[i + 1][1]) ) : _map->isPassable(x, y)) && 
			!(parentNode != nullptr && parentNode->_x == x && parentNode->_y == y))
		{
			Landscape8DirNode newNode(_map, x, y);
			search->AddSuccessor(newNode);
		}
	}
	return true;
}

int Landscape8DirNode::getX() const {return _x;}
int Landscape8DirNode::getY() const {return _y;}
